package finanz.kontrolle;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import classes.ArrayGenerico;
import classes.Funcoes;
import classes.Parametros;
import classes.SpinAdapterGenerico;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class ContaCadastroActivity extends MenuActivity implements OnClickListener {
	
	private SpinAdapterGenerico adapterPessoa;
	private SpinAdapterGenerico adapterBanco;
	private Parametros par = Parametros.getInstance();
	private ArrayGenerico[] pessoas;
	private ArrayGenerico[] bancos;
	private String id;
	private Spinner spnPessoa;
	private Spinner spnBanco;
	private EditText txtAgencia;
	private EditText txtConta;
	private EditText txtSaldoInicial;
	private EditText txtSaldoAtual;
	
	public void onCreate( Bundle bundle ) {
		super.onCreate( bundle );
		setContentView( R.layout.contacadastro );

		Bundle extras = getIntent().getExtras();

		id = extras.getString( "ContaID" );
		
		this.listarCombos();
		
		spnPessoa = ( Spinner ) findViewById( R.id.spPessoa );
		spnBanco = ( Spinner ) findViewById( R.id.spBanco );
		txtAgencia = ( EditText ) findViewById( R.id.txtAgencia );
		txtConta = ( EditText ) findViewById( R.id.txtConta );
		txtSaldoInicial = ( EditText ) findViewById( R.id.txtSaldoInicial );
		txtSaldoAtual = ( EditText ) findViewById( R.id.txtSaldoAtual );
		
		Button btnSalvarConta = ( Button ) findViewById( R.id.btnSalvarConta );
		btnSalvarConta.setOnClickListener( this );
		
		Button btnCancelar = ( Button ) findViewById( R.id.btnCancelar );
		btnCancelar.setOnClickListener( this );
	}
	
	public void onClick( View arg0 ) {
		int mensagem = R.string.msgSalvoSucesso;
		
		switch ( arg0.getId()  ) {
			case R.id.btnSalvarConta:
					if ( spnPessoa.getSelectedItemId() == 0 )
						 mensagem =  R.string.msgSelecionePessoa;
					else if ( spnBanco.getSelectedItemId() == 0 )
						 mensagem =  R.string.msgSelecioneBanco;
					else if ( txtAgencia.getText().length() <= 0 )
						 mensagem =  R.string.msgPreenchaAgencia;
					else if ( txtConta.getText().length() <= 0 )
						 mensagem =  R.string.msgPreenchaConta;
					else if ( txtSaldoInicial.getText().length() <= 0 )
						 mensagem =  R.string.msgPreenchaSaldoInicial;
					else if ( txtSaldoAtual.getText().length() <= 0 )
						 mensagem =  R.string.msgPreenchaSaldoAtual;
					else
						mensagem = this.salvar();
					
					if ( mensagem != R.string.msgSalvoSucesso ) {
						new AlertDialog.Builder( this )
						.setTitle( "Alerta" )
						.setMessage( mensagem )
						.setNeutralButton( "Ok", null).show();
					}
				break;
			case R.id.btnCancelar:
				this.volta();
				break;
		}
	}
	
	private void volta() {
		Intent i = new Intent( ContaCadastroActivity.this, ContaActivity.class );
		startActivity( i );
		finish();
	}
	
	protected int salvar( ) {
		int mensagem = R.string.msgSalvoSucesso;
		
		String strUrl = par.getUrl().toString() + getResources().getString( R.string.urlContaSalvar );
		
		HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost( strUrl );

	    try {
			List<NameValuePair> BancoValuePairs = new ArrayList<NameValuePair>(8);
			BancoValuePairs.add(new BasicNameValuePair("DatabaseID", par.getDatabase()));
			BancoValuePairs.add(new BasicNameValuePair("ContaID", id));
			BancoValuePairs.add(new BasicNameValuePair("PessoaID", pessoas[ (int) spnPessoa.getSelectedItemId() ].getID()));
			BancoValuePairs.add(new BasicNameValuePair("BancoID", bancos[ (int) spnBanco.getSelectedItemId() ].getID()));
			BancoValuePairs.add(new BasicNameValuePair("Agencia", txtAgencia.getText().toString()));
			BancoValuePairs.add(new BasicNameValuePair("Conta", txtConta.getText().toString()));
			BancoValuePairs.add(new BasicNameValuePair("SaldoAtual", txtSaldoAtual.getText().toString()));
			BancoValuePairs.add(new BasicNameValuePair("SaldoInicial", txtSaldoInicial.getText().toString()));
			httppost.setEntity(new UrlEncodedFormEntity(BancoValuePairs));

	        HttpResponse response = httpclient.execute(httppost);

	        Funcoes f = new Funcoes();
	        StringBuilder retorno = f.inputStreamToString( response.getEntity().getContent() );

	        if ( retorno.toString().equals( "1" ) ) {
				mensagem = R.string.msgSalvoSucesso;
				
				Toast t = Toast.makeText( this, mensagem, Toast.LENGTH_SHORT );
				t.setGravity( Gravity.CENTER, 0, 0 );
				t.show();
				
				this.volta();
	        } else
	        	mensagem = R.string.msgErroSalvar;
	        
	    } catch (IOException e) {
	    	mensagem = R.string.msgErroConectar;
	    }
		
	    return mensagem;
	}

	protected <adapter> void listarCombos(  ) {
		String strUrl = par.getUrl().toString() + getResources().getString( R.string.urlContaCadastro);
		
		HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost( strUrl );

	    try {
	        List<NameValuePair> ContaValuePairs = new ArrayList<NameValuePair>( 2 );
	        ContaValuePairs.add( new BasicNameValuePair( "DatabaseID", "" + par.getDatabase() ) );
	        
	        if ( !this.id.equals("0" ) )
	        	ContaValuePairs.add(new BasicNameValuePair("ContaID", id));
	        
	        httppost.setEntity( new UrlEncodedFormEntity( ContaValuePairs ) );

	        HttpResponse response = httpclient.execute( httppost );

	        Funcoes f = new Funcoes();
	        StringBuilder retorno = f.inputStreamToString( response.getEntity().getContent() );
	        
			try {
				
				spnPessoa = ( Spinner ) findViewById( R.id.spPessoa );
				spnBanco = ( Spinner ) findViewById( R.id.spBanco );
				txtAgencia = ( EditText ) findViewById( R.id.txtAgencia );
				txtConta = ( EditText ) findViewById( R.id.txtConta );
				txtSaldoInicial = ( EditText ) findViewById( R.id.txtSaldoInicial );
				txtSaldoAtual = ( EditText ) findViewById( R.id.txtSaldoAtual );
				
				JSONObject jo = new JSONObject( retorno.toString() );
				JSONArray arrayPessoa = jo.getJSONArray( "pessoa" );
				JSONArray arrayBanco = jo.getJSONArray( "banco" );
				
				pessoas = new ArrayGenerico[ arrayPessoa.length() ];
				
				for ( int p = 0; p < pessoas.length; p++ ) {
					JSONObject pessoa = new JSONObject( arrayPessoa.getJSONObject( p ).toString() );
					
					pessoas[ p ] = new ArrayGenerico();
					pessoas[ p ].setID( pessoa.getString( "PessoaID" ) );
					pessoas[ p ].setLabel( pessoa.getString( "Nome" ) );
				}
				
				adapterPessoa = new SpinAdapterGenerico( ContaCadastroActivity.this, android.R.layout.simple_spinner_item, pessoas);
				
				spnPessoa.setAdapter( adapterPessoa );
				
				 bancos = new ArrayGenerico[ arrayBanco.length() ];
				
				for ( int b = 0; b < bancos.length; b++ ) {
					JSONObject banco = new JSONObject( arrayBanco.getJSONObject( b ).toString() );
					
					bancos[ b ] = new ArrayGenerico();
					bancos[ b ].setID( banco.getString( "BancoID" ) );
					bancos[ b ].setLabel( banco.getString( "Nome" ) );
				}
				
				adapterBanco = new SpinAdapterGenerico( ContaCadastroActivity.this, android.R.layout.simple_spinner_item, bancos);
				
				spnBanco.setAdapter( adapterBanco );
				
				 if ( !this.id.equals("0" ) ) {

					 JSONObject dados = new JSONObject( jo.getJSONObject("dados").toString() );
					 
					int posPessoa = 0;
					for ( int p = 0; p < pessoas.length; p++ ) {
						if ( pessoas[ p ].getID().equals(dados.getString( "PessoaID" )) )
							posPessoa = p;
					}
					
					int posBanco = 0;
					for ( int b = 0; b < bancos.length; b++ ) {
						if ( bancos[ b ].getID().equals( dados.getString( "BancoID" ) ) )
							posBanco = b;
					}
					
					spnPessoa.setSelection( posPessoa );
					spnBanco.setSelection( posBanco );
					txtAgencia.setText( dados.getString( "Agencia" ) );
					txtConta.setText( dados.getString( "Conta" ) );
					txtSaldoInicial.setText( dados.getString( "SaldoInicial" ) );
					txtSaldoAtual.setText( dados.getString( "SaldoAtual" ) );
					 
				 } else {
					 if ( arrayPessoa.length() == 2 )
						 spnPessoa.setSelection( 1 );
					 
					 if ( arrayBanco.length() == 2 )
						 spnBanco.setSelection( 1 );
				 }
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
	    }  catch (IOException e) {
	    	e.printStackTrace();
		}

	}

}